package org.example.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.example.entity.ParamBody;
import org.example.service.GetOrders;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

@Slf4j
@Service
public class GetOrderImpl  implements GetOrders  {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod("https://erp.qizhishangke.com/api/Trade/TradeDownload/downTrade");

    @Override
    public void getOrderById(String id) {

    }

    @Override
    public void getOrdersByDate(String startTime, String  endTime, int[] shopIds) {
        postMethod.addRequestHeader("accept","*/*");
        //设置Content-Type，此处根据实际情况确定
        postMethod.addRequestHeader("Content-Type","application/json;charset=UTF-8");
        //必须设置下面这个Header
        //添加请求参数
        postMethod.addRequestHeader("token", "30f6f609614204a507edbe9204bc2b33$|goto");
        // 构建请求体参数
        ParamBody paramBody = new ParamBody();
        paramBody.setTids("");
        paramBody.setTimeZone("1");
        paramBody.setDownloadType("1");
        paramBody.setStartTime(startTime);
        paramBody.setEndTime(endTime);
        System.out.println("要抓取的店铺id为：" + Arrays.toString(shopIds));
        for (int i = 0; i < shopIds.length; i++) {
            paramBody.setShopId(shopIds[i]);
            // 对象转换为字符串
            String paramBodyStr = JSON.toJSONString(paramBody);
            postMethod.setRequestBody(paramBodyStr);
            try {
                httpClient.executeMethod(postMethod);
                InputStream is = postMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sb = new StringBuffer();
                String str = "";
                while ((str = br.readLine()) != null) {
                    sb.append(str);
                }
                String respMsg = sb.toString();
                System.out.println("返回的信息为：" + respMsg);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
